﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using XLabs.Caching;
using XLabs.Ioc;

namespace HalalCheck.ViewModels
{
    public class AllahNamesViewModel : BaseViewModel
    {
        private List<AllahNameItem> _allahNameList;

        public List<AllahNameItem> AllahNameList
        {
            get
            {
                return _allahNameList;

            }
            set
            {
                if (value != null)
                {
                    _allahNameList = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public AllahNamesViewModel()
        {
            GetAllahNames();
        }

        private async void GetAllahNames()
        {
            var allahKeyNames = "HalalCheck.Resources.names.txt";
            AllahNameList = Resolver.Resolve<ISimpleCache>().Get<List<AllahNameItem>>(allahKeyNames);
            if (AllahNameList == null)
            {
                var s = CultureInfo.CurrentCulture;

                #region How to load a text file embedded resource

                var assembly = typeof(AllahNamesViewModel).GetTypeInfo().Assembly;
                Stream stream =
                    assembly.GetManifestResourceStream(allahKeyNames);

                using (var reader = new StreamReader(stream, Encoding.UTF8, true))
                {
                    var temp = new List<AllahNameItem>();
                    while (!reader.EndOfStream)
                    {
                        var line = await reader.ReadLineAsync();

                        var values = line.Split('_');
                        var allah = new AllahNameItem
                        {
                            AllahName = values[0] + " - " + UpperFirst(values[1]) // + "\n" + values[2]

                        };
                        temp.Add(allah);
                    }
                    AllahNameList = temp;
                    Resolver.Resolve<ISimpleCache>().Set(allahKeyNames,AllahNameList);
                }
                #endregion
            }
        }

        static string UpperFirst(string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);
        }
    }

    public class AllahNameItem
    {
        public string AllahName { get; set; }
    }
}
